package com.party.mobile.biz.member;

import com.alibaba.fastjson.JSONObject;
import com.google.common.base.Strings;
import com.google.common.collect.Maps;
import com.party.authorization.manager.impl.RedisTokenManager;
import com.party.common.constant.Constant;
import com.party.common.utils.*;
import com.party.common.utils.img.CompressInput;
import com.party.core.exception.BusinessException;
import com.party.core.model.AuditStatus;
import com.party.core.model.BaseModel;
import com.party.core.model.YesNoStatus;
import com.party.core.model.city.Area;
import com.party.core.model.commune.CMemberInfo;
import com.party.core.model.fans.Fans;
import com.party.core.model.member.*;
import com.party.core.model.message.MessageSet;
import com.party.core.model.notify.MemberSet;
import com.party.core.model.system.SysConfig;
import com.party.core.service.city.IAreaService;
import com.party.core.service.commune.ICMemberInfoService;
import com.party.core.service.cos.CosBizService;
import com.party.core.service.fans.IFansService;
import com.party.core.service.member.*;
import com.party.core.service.message.IMessageSetService;
import com.party.core.service.notify.IMemberSetService;
import com.party.core.service.system.IMobileVerifyService;
import com.party.core.service.system.ISysConfigService;
import com.party.core.service.wechatPlatform.IWechatMerchantService;
import com.party.core.service.wechatPlatform.IWechatOpenMemberService;
import com.party.mobile.biz.currentUser.CurrentUserBizService;
import com.party.mobile.biz.verifyCode.VerifyCodeBizService;
import com.party.mobile.utils.RealmUtils;
import com.party.mobile.web.dto.login.input.ThirdPartyUserInput;
import com.party.mobile.web.dto.login.output.CurrentUser;
import com.party.mobile.web.dto.login.output.MemberOutput;
import com.party.mobile.web.dto.login.output.ThirdPartyUserOutput;
import com.party.mobile.web.dto.member.input.FillInfoInput;
import com.party.mobile.web.dto.member.input.RegisterInput;
import com.party.mobile.web.dto.member.output.MemberSetOutput;
import com.party.mobile.web.dto.member.output.MessageSetOutput;
import org.apache.commons.collections.CollectionUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.jdbc.UncategorizedSQLException;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.servlet.http.HttpServletRequest;
import java.text.SimpleDateFormat;
import java.util.*;

/**
 * 会员业务服务
 * party
 * Created by wei.li
 * on 2016/9/22 0022.
 */

@Service
public class MemberBizService {

    @Autowired
    private IAreaService areaService;

    @Autowired
    private IMemberService memberService;

    @Autowired
    private RedisTokenManager redisTokenManager;

    @Autowired
    private IThirdPartyUserService thirdPartyUserService;

    @Autowired
    private IMessageSetService messageSetService;

    @Autowired
    private CurrentUserBizService currentUserBizService;

    @Autowired
    private IIndustryService industryService;

    @Autowired
    private IFansService fansService;

    @Autowired
    private VerifyCodeBizService verifyCodeBizService;

    @Autowired
    private IPartnerMemberService partnerMemberService;
    @Autowired
    private CosBizService cosBizService;
    Logger logger = LoggerFactory.getLogger(getClass());
    @Autowired
    private IWechatMerchantService wechatMerchantService;
    @Autowired
    private IWechatOpenMemberService wechatOpenMemberService;
    @Autowired
    private IMobileVerifyService mobileVerifyService;
    @Autowired
    private IMemberAddressService memberAddressService;
    @Autowired
    private ISysConfigService sysConfigService;
    @Autowired
    private IMemberSetService memberSetService;
    @Autowired
    private IThirdPartyUserInfoService thirdPartyUserInfoService;

    @Autowired
    private ICMemberInfoService cMemberInfoService;

    @Autowired
    private IMemberGroupService memberGroupService;

    /**
     * 获取登陆会员输出视图
     *
     * @param member 会员信息
     * @return 会员输出视图
     */
    @Transactional
    public MemberOutput getLoginMember(Member member) {

        return getLoginMember(member, null);
    }

    /**
     * 获取登陆会员输出视图
     *
     * @param member 会员信息
     * @return 会员输出视图
     */
    @Transactional
    public MemberOutput getLoginMember(MemberGroup member) {
        return getLoginMember(member, null);
    }

    /**
     * 获取登陆会员输出视图
     *
     * @param member 会员信息
     * @param openId 第三方授权登陆id
     * @return 会员输出视图
     */
    @Transactional
    public MemberOutput getLoginMember(Member member, String openId) {
        MemberOutput memberOutput = MemberOutput.transform(member);
        //设置城市名字
        if (!Strings.isNullOrEmpty(member.getCity())) {
            Area area = areaService.get(member.getCity());
            if (null != area) {
                memberOutput.setCityId(area.getId());
                memberOutput.setCityName(area.getName());
            }
        }
        //设置行业名字
        if (!Strings.isNullOrEmpty(member.getIndustry())) {
            Industry industry = industryService.get(member.getIndustry());
            if (null != industry) {
                memberOutput.setIndustryId(industry.getId());
                memberOutput.setIndustry(industry.getName());
            }
        }
        CMemberInfo cMemberInfoOrg = cMemberInfoService.getByMemberId(member.getId());
        if (cMemberInfoOrg != null) {
            memberOutput.setHobby(cMemberInfoOrg.getHobby());
            memberOutput.setSynopsis(cMemberInfoOrg.getSynopsis());
            memberOutput.setAddress(cMemberInfoOrg.getAddress());
            memberOutput.setDistrict(cMemberInfoOrg.getDistrict());
        }
        //设置粉丝数和关注数
        Fans fans = new Fans();
        fans.setMemberId(member.getId());
        fans.setFollowerId(member.getId());
        memberOutput.setFansNum(fansService.countFans(fans));
        memberOutput.setFocusNum(fansService.countFocus(fans));
        //设置token
        String token = this.getToken(member, openId);
        memberOutput.setToken(token);

        //设置第三方登录id列表
//        memberOutput.setThirdPartyUserList(this.getThirdPartyUser(member.getId()));

        return memberOutput;
    }

    /**
     * 获取登陆会员输出视图
     *
     * @param member 会员信息
     * @param openId 第三方授权登陆id
     * @return 会员输出视图
     */
    @Transactional
    public MemberOutput getLoginMember(MemberGroup member, String openId) {
        MemberOutput memberOutput = MemberOutput.transform(member);
        //设置城市名字
        if (!Strings.isNullOrEmpty(member.getCity())) {
            Area area = areaService.get(member.getCity());
            if (null != area) {
                memberOutput.setCityId(area.getId());
                memberOutput.setCityName(area.getName());
            }
        }
        //设置行业名字
        if (!Strings.isNullOrEmpty(member.getIndustry())) {
            Industry industry = industryService.get(member.getIndustry());
            if (null != industry) {
                memberOutput.setIndustryId(industry.getId());
                memberOutput.setIndustry(industry.getName());
            }
        }
        //设置粉丝数和关注数
        Fans fans = new Fans();
        fans.setMemberId(member.getId());
        fans.setFollowerId(member.getId());
        memberOutput.setFansNum(fansService.countFans(fans));
        memberOutput.setFocusNum(fansService.countFocus(fans));
        //设置token
        String token = this.getToken(member, openId);
        memberOutput.setToken(token);

        //设置第三方登录id列表
//        memberOutput.setThirdPartyUserList(this.getThirdPartyUser(member.getId()));

        return memberOutput;
    }

    /**
     * 获取登陆凭证
     *
     * @param member 会员
     * @return 登陆凭证
     */
    public String getToken(Member member) {
        return getToken(member, null);
    }

    /**
     * 获取登陆凭证
     *
     * @param member 会员
     * @return 登陆凭证
     */
    public String getToken(Member member, String openId) {
        String oldToken = redisTokenManager.getToken(member.getId());
        if (StringUtils.isNotEmpty(oldToken)) {
            String memberId = redisTokenManager.getKeyByToken(oldToken);
            if (StringUtils.isNotEmpty(memberId)) {
                return oldToken;
            }
        }
        //获取登陆交互凭证
        CurrentUser currentUser = CurrentUser.transform(member);
        currentUser.setOpenId(openId);
        currentUser.setIsMemberGroup(YesNoStatus.NO.getCode());
        String newToken = RealmUtils.getToken(currentUser);
        redisTokenManager.createRelationship(member.getId(), newToken);
        return newToken;
    }

    /**
     * 获取登陆凭证
     *
     * @param member 会员
     * @return 登陆凭证
     */
    public String getToken(MemberGroup member, String openId) {
        String oldToken = redisTokenManager.getToken(member.getId());
        if (StringUtils.isNotEmpty(oldToken)) {
            String memberId = redisTokenManager.getKeyByToken(oldToken);
            if (StringUtils.isNotEmpty(memberId)) {
                return oldToken;
            }
        }
        //获取登陆交互凭证
        CurrentUser currentUser = CurrentUser.transform(member);
        currentUser.setOpenId(openId);
        currentUser.setIsMemberGroup(YesNoStatus.YES.getCode());
        String newToken = RealmUtils.getToken(currentUser);
        redisTokenManager.createRelationship(member.getId(), newToken);
        return newToken;
    }

    /**
     * 注册会员
     *
     * @param registerInput 注册输入视图
     */
    @Transactional
    public MemberOutput register(RegisterInput registerInput) {

        //验证手机号是否存在
        Member dbMember = memberService.findByPhone(registerInput.getPhone(), Constant.MEMBER_PERSONAL);
        if (null != dbMember) {
            throw new BusinessException(PartyCode.PHONE_EXIST, "手机号码已经注册");
        }
        Member member = createMember(Constant.MEMBER_PERSONAL);

        member.setMobile(registerInput.getPhone());
        member.setPassword(PasswordUtils.encryptPassword(registerInput.getPassword()));
        member.setCountryCode(registerInput.getCountryCode());
        memberService.update(member);

        MemberOutput memberOutput = MemberOutput.transform(member);

        //设置第三方登录id列表
//        memberOutput.setThirdPartyUserList(this.getThirdPartyUser(member.getId()));

        String token = this.getToken(member);
        memberOutput.setToken(token);
        return memberOutput;
    }

    /**
     * 通过第三方账户登录注册
     *
     * @param thirdPartyUserInput 第三方登陆输入视图
     * @param request
     */
    @Transactional
    public MemberOutput thirdPartyUserLogin(ThirdPartyUserInput thirdPartyUserInput, HttpServletRequest request) {
        logger.info("thirdPartyUserInput详细信息：{}", JSONObject.toJSONString(thirdPartyUserInput));
        boolean openIdFound = false; // 是否通过openID找到了授权记录
        //审核状态
        Integer checkStatus = 3;
        //查找用户
        ThirdPartyUser tUser = null;
        tUser = thirdPartyUserService.getByOpenId(thirdPartyUserInput.getOpenId());
        if (tUser == null) {
            if (!Strings.isNullOrEmpty(thirdPartyUserInput.getUnionId())) {
                tUser = thirdPartyUserService.getByUnionId(thirdPartyUserInput.getUnionId());
            }
        } else {
            openIdFound = true;
        }

        Member member;
        //第三方账号信息不为空
        if (null != tUser) {
            member = memberService.get(tUser.getMemberId());
            try {
                if (null == member) {
                    logger.error("tp_login异常：thirdPartyUserInput--" + JSONObject.toJSONString(thirdPartyUserInput));
                }
            } catch (Exception e) {
                e.printStackTrace();
            }

            //审核状态返回---行知公社业务
            if (StringUtils.isNotEmpty(member.getMobile()) &&
                    (ThirdPartyUserInput.TPLOGIN_SIGN_TYPE_INTEGRAL.equals(thirdPartyUserInput.getSign())
                            || StringUtils.isNotEmpty(thirdPartyUserInput.getPmId()))) {
                CMemberInfo byMemberId = cMemberInfoService.getByMemberId(member.getId());
                if (byMemberId == null) {
                    checkStatus = CMemberInfo.CHECK_STATUS_ADOPT;
                } else {
                    checkStatus = byMemberId.getCheckStatus();
                }
            }

            boolean bResult = false;
//            //如果之前用户没有头像，则补充头像信息
//            if (Strings.isNullOrEmpty(member.getLogo()) && !Strings.isNullOrEmpty(thirdPartyUserInput.getLogo())) {
//                member.setLogo(thirdPartyUserInput.getLogo());
//
//                bResult = true;
//            }
            //更新头像
            updateLogo(member, thirdPartyUserInput.getLogo());
            //如果之前用户没有名字，则补充用户名字
            if (Strings.isNullOrEmpty(member.getRealname()) && !Strings.isNullOrEmpty(thirdPartyUserInput.getRealname())) {
                //过滤Emoji表情
                member.setRealname(PinyinUtil.filterEmoji(thirdPartyUserInput.getRealname(), ""));
                member.setPinyin(PinyinUtil.hanziToPinyin(member.getRealname(), ""));
                bResult = true;
            }

//            if (Strings.isNullOrEmpty(tUser.getUnionId()) && !Strings.isNullOrEmpty(thirdPartyUserInput.getUnionId())) {
//                tUser.setUnionId(thirdPartyUserInput.getUnionId());
//                thirdPartyUserService.update(tUser);
//            }

            if (null == member.getType() && !YesNoStatus.YES.getCode().equals(member.getIsPartner())
                    && !YesNoStatus.YES.getCode().equals(member.getIsCosponsor())) {
                member.setType(Constant.MEMBER_PERSONAL);
                bResult = true;
            }
            //更新unionId
            if (!Strings.isNullOrEmpty(thirdPartyUserInput.getUnionId())) {
                boolean updateFlag = false;
                if (Strings.isNullOrEmpty(tUser.getUnionId())) {
                    updateFlag = true;
                } else if (!Strings.isNullOrEmpty(tUser.getUnionId()) && !tUser.getUnionId().equals(thirdPartyUserInput.getUnionId())) {
                    updateFlag = true;
                }
                if (updateFlag) {
                    tUser.setUnionId(thirdPartyUserInput.getUnionId());
                    thirdPartyUserService.update(tUser);
                }
            }
            //更新会员信息
            if (bResult) {
                memberService.update(member);
            }
            if (!Strings.isNullOrEmpty(thirdPartyUserInput.getUnionId())) {
                // 查找授权记录是否是当前这个用户类型的，比如前文找到的是APP的，但是当前是小程序的，这时是需要保存一条小程序的授权记录的，只是对应的是同一个用户
                ThirdPartyUser unionIdTUser = thirdPartyUserService.getByUnionIdType(thirdPartyUserInput.getUnionId(), thirdPartyUserInput.getType());
                if (unionIdTUser == null) {
                    createTpUser(member, thirdPartyUserInput);
                } else {
                    // 查找授权记录是否是当前这个用户类型的，比如前文找到的是同行者的，但是当前是创毅行的，这时是需要保存一条创毅行的授权记录的，只是对应的是同一个用户
                    if (openIdFound == false) {
                        createTpUser(member, thirdPartyUserInput);
                    }
                    // tUser.setThirdPartyId(thirdPartyUserInput.getOpenId());
                    // thirdPartyUserService.update(tUser);
                }
            }

            try {
                ThirdPartyUserInfo thirdPartyUserInfo = thirdPartyUserInfoService.findByThirdPartyUserId(tUser.getId());
                if (null == thirdPartyUserInfo) {
                    thirdPartyUserInfo = new ThirdPartyUserInfo();
                    thirdPartyUserInfo.setThirdPartyUserId(tUser.getId());
                    thirdPartyUserInfo.setNickname(PinyinUtil.filterEmoji(thirdPartyUserInput.getRealname(), ""));
                    thirdPartyUserInfo.setLogo(thirdPartyUserInput.getLogo());
                    thirdPartyUserInfoService.insert(thirdPartyUserInfo);
                }
            } catch (UncategorizedSQLException e) {

            } catch (Exception e) {
                logger.error("保存授权信息异常", e);
            }
        } else {
            member = registerMember(thirdPartyUserInput, request);
        }

        String pmId = "";

        if (StringUtils.isNoneBlank(thirdPartyUserInput.getPmId()) ||
                ThirdPartyUserInput.TPLOGIN_SIGN_TYPE_INTEGRAL.equals(thirdPartyUserInput.getSign())) {
            //是否和行知公社的机构存在关系，包括其子账号
            MemberGroup xingZheGongSheMemberGroup = this.getXingZheGongSheMemberGroup();
            HashMap<String, Object> param = Maps.newHashMap();
            param.put("partnerId", xingZheGongSheMemberGroup.getId());
            param.put("memberId", member.getId());
            List<PartnerMember> memberPartnersTo = partnerMemberService.getMemberPartnersTo(param);


            //默认返回主账号的pmId
            PartnerMember mainOrg = partnerMemberService.getMainOrg(member.getId(), xingZheGongSheMemberGroup.getId());
            if (mainOrg != null) {
                pmId = mainOrg.getId();
            }
            if (memberPartnersTo.size() == 0) {    //不存在关系
                //行知公社授权成功插入 机构用户关系
                if (StringUtils.isNoneBlank(thirdPartyUserInput.getPmId())) {
                    //---------------------------邀请注册
                    PartnerMember partnerMember = partnerMemberService.get(thirdPartyUserInput.getPmId());
                    if (partnerMember.getMemberId() != member.getId()) {
                        PartnerMember partner = partnerMemberService.findByPartnerAndMember(partnerMember.getPartnerId(), member.getId());
                        if (null == partner) {
                            partner = new PartnerMember();
                            BaseModel.preInsert(partner);
                            partner.setPartnerId(partnerMember.getPartnerId());
                            partner.setMemberId(member.getId());
                            if (null == mainOrg) {
                                partner.setPartnerType(PartnerMember.IS_MAIN_TYPE);
                            }
                            partnerMemberService.insert(partner);
                            logger.info("邀请注册---行知公社授权插入用户机构关系成功pmid：" + partner.getId());
                        }
                        pmId = partner.getId();
                    }
                } else if (ThirdPartyUserInput.TPLOGIN_SIGN_TYPE_INTEGRAL.equals(thirdPartyUserInput.getSign())) {
                    //---------------------------扫码注册或搜索小程序注册
                    PartnerMember partner = partnerMemberService.findByPartnerAndMember(xingZheGongSheMemberGroup.getId(), member.getId());
                    if (partner == null) {
                        partner = new PartnerMember();
                        BaseModel.preInsert(partner);
                        partner.setPartnerId(xingZheGongSheMemberGroup.getId());
                        if (null == mainOrg) {
                            partner.setPartnerType(PartnerMember.IS_MAIN_TYPE);
                        }
                        partner.setMemberId(member.getId());
                        partnerMemberService.insert(partner);
                        logger.info("自主注册---行知公社授权插入用户机构关系成功pmid：" + partner.getId());
                    }
                    pmId = partner.getId();
                }
            }
            //如果没有主账号的pmId，默认给行知公社的-----这个情况不正常
            if (StringUtils.isEmpty(pmId)) {
                PartnerMember xzgsP = partnerMemberService.findByPartnerAndMember(xingZheGongSheMemberGroup.getId(), member.getId());
                if (xzgsP != null) {
                    pmId = mainOrg.getId();
                }
            }
        }
        MemberOutput memberOutput = getLoginMember(member, thirdPartyUserInput.getOpenId());
        memberOutput.setPmId(pmId);
        memberOutput.setCheckStatus(checkStatus);
        return memberOutput;
    }

    /**
     * 通过第三方账号授权注册会员
     *
     * @param thirdPartyUserInput
     * @param request
     * @return
     */
    @Transactional
    public Member registerMember(ThirdPartyUserInput thirdPartyUserInput, HttpServletRequest request) {
        Member member = createMember(Constant.MEMBER_PERSONAL);

        //如果之前用户没有头像，则补充头像信息
        if (Strings.isNullOrEmpty(member.getLogo()) && !Strings.isNullOrEmpty(thirdPartyUserInput.getLogo())) {
            member.setLogo(thirdPartyUserInput.getLogo());
        }
        //如果之前用户没有名字，则补充用户名字
        if (Strings.isNullOrEmpty(member.getRealname()) && !Strings.isNullOrEmpty(thirdPartyUserInput.getRealname())) {
            //过滤Emoji表情
            member.setRealname(PinyinUtil.filterEmoji(thirdPartyUserInput.getRealname(), ""));
            member.setPinyin(PinyinUtil.hanziToPinyin(member.getRealname(), ""));
        }
        memberService.update(member);

        createTpUser(member, thirdPartyUserInput);
        return member;
    }

    private ThirdPartyUser createTpUser(Member member, ThirdPartyUserInput thirdPartyUserInput) {
        ThirdPartyUser tUser = new ThirdPartyUser();
        tUser.setType(thirdPartyUserInput.getType());//第三方账号类型
        tUser.setMemberId(member.getId());
        tUser.setThirdPartyId(thirdPartyUserInput.getOpenId());
        // tUser.setType(thirdPartyUserInput.getType());
        tUser.setDelFlag(BaseModel.DEL_FLAG_NORMAL);
        tUser.setUnionId(thirdPartyUserInput.getUnionId());
        //保存商户信息
        if (!Strings.isNullOrEmpty(thirdPartyUserInput.getMerchantId())) {
            //获取微信appid
            String authorizerAppid = wechatMerchantService.getAppid(thirdPartyUserInput.getMerchantId());
            if (null == authorizerAppid) {
                tUser.setAppId(wechatOpenMemberService.getSystem().getAuthorizerAppid());
            } else {
                tUser.setAppId(authorizerAppid);
            }
        } else if (StringUtils.isNotEmpty(thirdPartyUserInput.getAppId())) { // 指定APPID
            tUser.setAppId(thirdPartyUserInput.getAppId());
        }
        //默认为平台
        else {
            tUser.setAppId(wechatOpenMemberService.getSystem().getAuthorizerAppid());
        }
        thirdPartyUserService.insert(tUser);//保存微信登陆openID

        try {
            ThirdPartyUserInfo userInfo = new ThirdPartyUserInfo();
            userInfo.setNickname(PinyinUtil.filterEmoji(thirdPartyUserInput.getRealname(), ""));
            userInfo.setThirdPartyUserId(tUser.getId());
            userInfo.setLogo(thirdPartyUserInput.getLogo());
            thirdPartyUserInfoService.insert(userInfo);
        } catch (UncategorizedSQLException e) {

        } catch (Exception e) {
            logger.error("保存授权信息异常", e);
        }

        return tUser;
    }

    /**
     * 绑定手机号 该方法已经弃用，请尽快切换使用bindPhoneNew
     *
     * @param mobile     手机号
     * @param realname   姓名
     * @param company    公司名
     * @param jobTitle   职位
     * @param industryID 行业主键id
     * @param request
     * @return
     */
    /*@Transactional
    @Deprecated
    public MemberOutput bindPhone(String mobile, String realname, String company, String jobTitle, String industryID, HttpServletRequest request) {

        CurrentUser currentUser = currentUserBizService.getCurrentUser(request);//根据token获取当前登录用户
        ThirdPartyUser tUser = thirdPartyUserService.getByOpenId(currentUser.getOpenId());//获取第三方授权用户实体
        Member memberNew = memberService.get(currentUser.getId());//根据当前登录用户获取会员实体
        Member dbMember = memberService.findByPhone(mobile);//根据用户输入手机号获取的会员实体

        //根据当前登录用户不能获取第三方授权登陆用户实体，判定为没有使用第三方授权账号登陆
        if (null == tUser) {
            throw new BusinessException(PartyCode.BIND_PHONE_UNUSE_OPEN_ID, "未使用第三方授权账号登陆");
        }

        //已经绑定了手机号，就不能再绑定新手机号
        if (!Strings.isNullOrEmpty(memberNew.getMobile())) {
            throw new BusinessException(PartyCode.BIND_PHONE_HAS_BINDED, "已经绑定手机号");
        }

        MemberOutput memberOutput = null;
        if (null != dbMember)//当前手机号已经注册
        {
            //更新第三方授权信息 修改用户id字段
            tUser.setMemberId(dbMember.getId());
            thirdPartyUserService.update(tUser);
            //逻辑删除原用户信息
            memberService.deleteLogic(memberNew.getId());

            //删除token
            String oldToken = request.getHeader(Constant.HTTP_HEADER_NAME);
            redisTokenManager.delRelationshipByToken(oldToken);

            //重新绑定token
            memberOutput = MemberOutput.transform(dbMember);
            String token = this.getToken(dbMember, currentUser.getOpenId());
            memberOutput.setToken(token);
        } else {//当前手机号未注册，填入相关用户信息
            memberNew.setMobile(mobile);
            //所有用户自主填写的内容都需过滤Emoji表情
            if (!Strings.isNullOrEmpty(realname)) {
                memberNew.setRealname(PinyinUtil.filterEmoji(realname, ""));
                memberNew.setPinyin(PinyinUtil.hanziToPinyin(memberNew.getRealname(), ""));
            }
            if (!Strings.isNullOrEmpty(company)) {
                memberNew.setCompany(PinyinUtil.filterEmoji(company, ""));
            }
            if (!Strings.isNullOrEmpty(industryID)) {
                memberNew.setIndustry(industryID);
            }
            if (!Strings.isNullOrEmpty(jobTitle)) {
                memberNew.setJobTitle(PinyinUtil.filterEmoji(jobTitle, ""));
            }
            memberService.update(memberNew);

            //删除token
            String oldToken = request.getHeader(Constant.HTTP_HEADER_NAME);
            redisTokenManager.delRelationshipByToken(oldToken);

            //重新绑定token
            memberOutput = MemberOutput.transform(memberNew);
            String token = this.getToken(memberNew, currentUser.getOpenId());
            memberOutput.setToken(token);
        }

        //设置第三方登录id列表
//        memberOutput.setThirdPartyUserList(this.getThirdPartyUser(currentUser.getId()));

        return memberOutput;
    }*/

    /**
     * 创建会员，并初始化
     *
     * @return 会员实体
     */
    @Transactional
    public Member createMember(Integer type) {
        Member member = new Member();
        member.setUserStatus(Integer.parseInt(AuditStatus.AUDITING.getCode()));//默认未审核
        // 联合发起
        member.setIsCopartner(YesNoStatus.NO_NEW.getCode());
        // 合作商
        member.setIsPartner(YesNoStatus.NO.getCode());
        // 管理员
        member.setIsAdmin(YesNoStatus.NO.getCode());
        // 达人
        member.setIsExpert(YesNoStatus.NO.getCode());
        // 分销商
        member.setIsDistributor(YesNoStatus.NO.getCode());
        // 合作渠道
        member.setIsCosponsor(YesNoStatus.NO.getCode());
        member.setPicNum(0);
        member.setIsOpen(YesNoStatus.NO.getCode());
        member.setPassword(PasswordUtils.encryptPassword(Constant.DEFALT_PASSWORD));
        member.setType(type);
        memberService.insert(member);//保存会员

        return member;
    }

    /**
     * 绑定手机 新
     * 2017-06-26
     *
     * @param mobile  手机号
     * @param request
     * @return 绑定手机
     */
    @Transactional
    public Map<String, Object> bindPhoneNew(String mobile, HttpServletRequest request) {
        CurrentUser curUser = currentUserBizService.getCurrentUser(request);
        Member curMember = memberService.get(curUser.getId());
        //根据手机号查找用户
        Member mobileMember = memberService.findByPhone(mobile, Constant.MEMBER_PERSONAL);
        Map<String, Object> output = Maps.newHashMap();
        //若用户存在
        if (null != mobileMember) {
            //当前用户不等于手机查到的用户
            if (!mobileMember.getId().equals(curMember.getId())) {
                //手机查找到的用户是合作商账户，不允许合并
                if (mobileMember.getIsPartner().equals(YesNoStatus.YES.getCode())) {
                    throw new BusinessException(PartyCode.PHONE_EXIST, "该手机已被绑定，请确认");
                }
                //如果当前用户是第三方授权账户
                if (CurrentUser.isThirdparty(curUser)) {
                    //查找第三方表中当前用户的记录
                    List<ThirdPartyUser> tUsers = thirdPartyUserService.getByMemberId(curUser.getId());
                    if (null != tUsers && tUsers.size() > 0) {
                        //更新第三方表中当前用户的记录为手机号查询到的用户
                        for (ThirdPartyUser tUser : tUsers) {
                            tUser.setMemberId(mobileMember.getId());
                            thirdPartyUserService.update(tUser);
                        }
                    }

                    //更新登录用户信息
                    //删除token
                    String oldToken = request.getHeader(com.party.authorization.utils.Constant.HTTP_HEADER_NAME);
                    redisTokenManager.delRelationshipByToken(oldToken);

                    //重新绑定token
                    String token = this.getToken(mobileMember);
                    output.put("token", token);
                    output.put("memberId", mobileMember.getId());
                } else {
                    /**
                     * 不是第三方用户,此处不处理合并操作，
                     * 因为现机构账号是使用用户名密码登录的，若合并其他账号的手机，会使当前用户混乱
                     */
                    throw new BusinessException(PartyCode.PHONE_EXIST, "该手机已被绑定，请确认");
                }
            }
        } else {//若用户不存在
            //更新当前用户的手机号为传入的手机
            curMember.setMobile(mobile);
            memberService.update(curMember);
            output.put("memberId", curMember.getId());
        }
        return output;
    }

    /**
     * 抽取公用的绑定封装
     *
     * @param mobile 手机
     * @param vCode  验证码
     */
    public CurrentUser bindPhoneBiz(String mobile, String vCode, HttpServletRequest request) throws BusinessException {
        CurrentUser currentUser = currentUserBizService.getCurrentUser(request);

        if (!Strings.isNullOrEmpty(mobile) && !Strings.isNullOrEmpty(vCode)) {
            // 加短信开关
            boolean isVerify = sysConfigService.isVerifySms();
            if (isVerify) {
                //验证码验证
                boolean verifyResult = verifyCodeBizService.verify(mobile, vCode);
                if (verifyResult) {
                    //绑定手机号
                    Map<String, Object> map = bindPhoneNew(mobile, request);
                    //如果当前用户有合并操作需重新赋值
                    if (null != map.get("memberId") && !map.get("memberId").equals(currentUser.getId())) {
                        currentUser = currentUserBizService.getCurrentUserByToken((String) map.get("token"));
                    }
                } else {
                    throw new BusinessException("手机号和验证码不匹配");
                }
            }
        }
        return currentUser;
    }

    public CurrentUser bindPhoneBiz2(String mobile, String vCode, String countryCode, HttpServletRequest request)
            throws BusinessException {
        CurrentUser currentUser = currentUserBizService.getCurrentUser(request);
        Member member = memberService.get(currentUser.getId());

        // 加短信开关
        if (Strings.isNullOrEmpty(member.getMobile())) {
            boolean isVerify = sysConfigService.isVerifySms();
            if (isVerify) {
                //是否需要验证
                boolean isNeedVerify = mobileVerifyService.isNeedVerify(countryCode);
                if (isNeedVerify) {
                    //验证码验证
                    boolean verifyResult = verifyCodeBizService.verify(mobile, vCode);
                    if (!verifyResult) {
                        throw new BusinessException("手机号和验证码不匹配");
                    }
                }
            }

            //绑定手机号
            Map<String, Object> map = bindPhoneNew(mobile, request);
            //如果当前用户有合并操作需重新赋值
            if (null != map.get("memberId") && !map.get("memberId").equals(currentUser.getId())) {
                currentUser = currentUserBizService.getCurrentUserByToken((String) map.get("token"));
            }
        }
        return currentUser;
    }

    /**
     * 加国际后的验证验证码
     *
     * @param mobile
     * @param code
     * @param countryCode
     * @return
     */
    public boolean verifyCode(String mobile, String code, String countryCode) {
        //是否需要验证
        boolean isNeedVerify = mobileVerifyService.isNeedVerify(countryCode);
        boolean verifyResult = true;
        if (isNeedVerify) {
            //验证码验证
            verifyResult = verifyCodeBizService.verify(mobile, code);
        }
        return verifyResult;
    }

    /**
     * 如果当前用户信息为空 更新当前用户的信息
     *
     * @param member
     * @param curMember
     */
    public Member updateImportantInfo(Member member, Member curMember) {
        //所有用户自主填写的内容都需过滤Emoji表情
        //昵称
        if (!Strings.isNullOrEmpty(member.getRealname()) && Strings.isNullOrEmpty(curMember.getRealname())) {
            curMember.setRealname(PinyinUtil.filterEmoji(member.getRealname(), ""));
            curMember.setPinyin(PinyinUtil.hanziToPinyin(member.getRealname(), ""));
        }
        //公司
        if (!Strings.isNullOrEmpty(member.getCompany()) && Strings.isNullOrEmpty(curMember.getCompany())) {
            curMember.setCompany(PinyinUtil.filterEmoji(member.getCompany(), ""));
        }
        //职位
        if (!Strings.isNullOrEmpty(member.getJobTitle()) && Strings.isNullOrEmpty(curMember.getJobTitle())) {
            curMember.setJobTitle(PinyinUtil.filterEmoji(member.getJobTitle(), ""));
        }
        //微信号
        if (!Strings.isNullOrEmpty(member.getWechatNum()) && Strings.isNullOrEmpty(curMember.getWechatNum())) {
            curMember.setWechatNum(PinyinUtil.filterEmoji(member.getWechatNum(), ""));
        }
        //行业
        if (!Strings.isNullOrEmpty(member.getIndustry()) && Strings.isNullOrEmpty(curMember.getIndustry())) {
            curMember.setIndustry(member.getIndustry());
        }
        //城市
        if (!Strings.isNullOrEmpty(member.getCity()) && Strings.isNullOrEmpty(curMember.getCity())) {
            curMember.setCity(member.getCity());
        }
        if (!Strings.isNullOrEmpty(member.getFullname()) && Strings.isNullOrEmpty(curMember.getFullname())) {
            curMember.setFullname(member.getFullname());
        }
        // 性别
        if (null != member.getSex()) {
            curMember.setSex(member.getSex());
        }
        if (null != member.getCountryCode()) {
            curMember.setCountryCode(member.getCountryCode());
        }
        memberService.update(curMember);
        return curMember;
    }

    /**
     * 更新当前用户的信息
     *
     * @param member    新
     * @param curMember 旧
     */
    public Member updateImportantInfo2(Member member, Member curMember) {
        //所有用户自主填写的内容都需过滤Emoji表情
        //昵称
        if (!Strings.isNullOrEmpty(member.getRealname())) {
            curMember.setRealname(PinyinUtil.filterEmoji(member.getRealname(), ""));
            curMember.setPinyin(PinyinUtil.hanziToPinyin(member.getRealname(), ""));
        }
        //公司
        if (!Strings.isNullOrEmpty(member.getCompany())) {
            curMember.setCompany(PinyinUtil.filterEmoji(member.getCompany(), ""));
        }
        //职位
        if (!Strings.isNullOrEmpty(member.getJobTitle())) {
            curMember.setJobTitle(PinyinUtil.filterEmoji(member.getJobTitle(), ""));
        }
        //微信号
        if (!Strings.isNullOrEmpty(member.getWechatNum())) {
            curMember.setWechatNum(PinyinUtil.filterEmoji(member.getWechatNum(), ""));
        }
        //行业
        if (!Strings.isNullOrEmpty(member.getIndustry())) {
            curMember.setIndustry(member.getIndustry());
        }
        //城市
        if (!Strings.isNullOrEmpty(member.getCity())) {
            curMember.setCity(member.getCity());
        }
        if (!Strings.isNullOrEmpty(member.getFullname())) {
            curMember.setFullname(member.getFullname());
        }
        // 性别
        if (null != member.getSex()) {
            curMember.setSex(member.getSex());
        }
        if (null != member.getCountryCode()) {
            curMember.setCountryCode(member.getCountryCode());
        }
        memberService.update(curMember);
        return curMember;
    }

    /**
     * 根据当前用户主键id，获取openId列表
     *
     * @param currentUserId 当前用户主键id
     * @return
     */
    public List<ThirdPartyUserOutput> getThirdPartyUser(String currentUserId) {
        ThirdPartyUser thirdPartyUser = new ThirdPartyUser();
        thirdPartyUser.setMemberId(currentUserId);
//        thirdPartyUser.setDelFlag("0");

        List<ThirdPartyUser> dbList = thirdPartyUserService.list(thirdPartyUser);

        if (!CollectionUtils.isEmpty(dbList)) {
            List<ThirdPartyUserOutput> listOutputList = LangUtils.transform(dbList, input -> {
                ThirdPartyUserOutput listOutput = ThirdPartyUserOutput.transform(input);
                return listOutput;
            });
            return listOutputList;
        }
        return Collections.EMPTY_LIST;

    }

    public MemberOutput fillInfo(FillInfoInput fillInfoInput, String curId) throws Exception {
        //验证当前登录用户数据
        Member dbMember = memberService.get(curId);
        if (null == dbMember) {
            throw new BusinessException(PartyCode.CURRENT_USER_DATA_ERROR, "当前用户数据错误,请重新登录");
        }
        //验证地区Area数据
        if (!Strings.isNullOrEmpty(fillInfoInput.getCity())) {

            Area area = areaService.get(fillInfoInput.getCity());
            if (null == area) {
                throw new BusinessException(PartyCode.AREA_DATA_ERROR, "当前输入的地区id有误，没有找到相应的地区信息");
            }
        }

        //验证行业industry数据
        if (!Strings.isNullOrEmpty(fillInfoInput.getIndustry())) {
            Industry industry = industryService.get(fillInfoInput.getIndustry());
            if (null == industry) {
                throw new BusinessException(PartyCode.INDUSTRY_DATA_ERROR, "当前输入的行业id有误，没有找到相应的行业信息");
            }
        }

        FillInfoInput.transform(dbMember, fillInfoInput);
        //所有用户自主填写的内容都需过滤Emoji表情
        dbMember.setRealname(PinyinUtil.filterEmoji(dbMember.getRealname(), ""));
        dbMember.setPinyin(PinyinUtil.hanziToPinyin(dbMember.getRealname(), ""));
        dbMember.setFullname(PinyinUtil.filterEmoji(dbMember.getFullname(), ""));
        dbMember.setCompany(PinyinUtil.filterEmoji(dbMember.getCompany(), ""));
        dbMember.setJobTitle(PinyinUtil.filterEmoji(dbMember.getJobTitle(), ""));
        dbMember.setWechatNum(PinyinUtil.filterEmoji(dbMember.getWechatNum(), ""));
        dbMember.setWantRes(PinyinUtil.filterEmoji(dbMember.getWantRes(), ""));

        memberService.update(dbMember);

        MemberOutput output = this.getLoginMember(dbMember);

        return output;
    }

    /**
     * 重置用户手机号
     *
     * @param mobile     手机号
     * @param verifyCode 验证码
     * @param request
     * @return
     * @throws BusinessException
     */
    public void resetMobile(String mobile, String verifyCode, String countryCode, HttpServletRequest request) {
        //加短信开关
        boolean isNeedVerify = sysConfigService.isVerifySms();
        if (isNeedVerify) {
            // 验证验证码
            boolean isVerify = verifyCode(mobile, verifyCode, countryCode);
            if (!isVerify) {
                throw new BusinessException(PartyCode.VERIFY_CODE_ERROR, "手机号和验证码不匹配");
            }
        }

        CurrentUser currentUser = currentUserBizService.getCurrentUser(request);
        //验证当前登录用户数据
        Member dbMember = memberService.get(currentUser.getId());
        if (null == dbMember) {
            throw new BusinessException(PartyCode.CURRENT_USER_DATA_ERROR, "当前用户数据错误,请重新登录");
        }
        //验证手机号是否跟当前用户一致
        if (mobile.equals(dbMember.getMobile())) {
            throw new BusinessException(PartyCode.RESET_MOBILE_SAME_PHONE_CODE, "该手机号与当前登录用户手机号一致，不用修改");
        }

        if (null == dbMember.getType()) {
            throw new BusinessException(100, "当前用户的类型为空，不能更换手机号");
        }
        Member member = memberService.findByPhone(mobile, dbMember.getType());
        if (null != member) {
            throw new BusinessException(100, "该手机号已绑定用户，不能更换");
        }

        dbMember.setMobile(mobile);
        dbMember.setCountryCode(countryCode);
        memberService.update(dbMember);
        redisTokenManager.delRelationshipByKey(dbMember.getId());
    }

    /**
     * 重置用户头像
     *
     * @param logo    用户头像url
     * @param request
     * @return
     * @throws BusinessException
     */
    public boolean resetAvata(String logo, HttpServletRequest request) throws BusinessException {
        Member dbMember = null;
        MemberGroup memberGroup = null;
        CurrentUser currentUser = currentUserBizService.getCurrentUser(request);
        if (null != currentUser.getIsMemberGroup() && YesNoStatus.YES.getCode().equals(currentUser.getIsMemberGroup())) {
            memberGroup = memberGroupService.get(currentUser.getId());
        } else {
            dbMember = memberService.get(currentUser.getId());
        }

        //验证当前登录用户数据
        if (null == dbMember && null == memberGroup) {
            throw new BusinessException(PartyCode.CURRENT_USER_DATA_ERROR, "当前用户数据错误,请重新登录");
        }

        if (null != dbMember) {
            dbMember.setBacklogo(dbMember.getLogo());
            dbMember.setLogo(logo);

            memberService.update(dbMember);
        } else if (null != memberGroup) {
            memberGroup.setLogo(logo);

            memberGroupService.update(memberGroup);
        }
        return true;
    }

    /**
     * 设置用户资料是否公开
     *
     * @param isOpen  用户资料是否公开，0：否，1：是
     * @param request
     * @return
     * @throws BusinessException
     */
    public boolean setOpenInfo(Integer isOpen, HttpServletRequest request) throws BusinessException {
        CurrentUser currentUser = currentUserBizService.getCurrentUser(request);

        Member dbMember = memberService.get(currentUser.getId());

        //验证当前登录用户数据
        if (null == dbMember) {
            throw new BusinessException(PartyCode.CURRENT_USER_DATA_ERROR, "当前用户数据错误,请重新登录");
        }

        dbMember.setIsOpen(isOpen);

        memberService.update(dbMember);

        return true;
    }

    /**
     * 获取push消息通知设置信息
     *
     * @param request
     * @return
     */
    public MessageSetOutput getMessageSetInfo(HttpServletRequest request) {
        CurrentUser currentUser = currentUserBizService.getCurrentUser(request);

        Member dbMember = memberService.get(currentUser.getId());
        //验证当前登录用户数据
        if (null == dbMember) {
            throw new BusinessException(PartyCode.CURRENT_USER_DATA_ERROR, "当前用户数据错误,请重新登录");
        }

        MessageSet messageSet = messageSetService.findByMemberId(dbMember.getId());
        //如果之前没有设置，则给加上
        if (null == messageSet) {
            messageSet = new MessageSet();
            messageSet.setLoveTip(YesNoStatus.YES.getCode());
            messageSet.setCommentTip(YesNoStatus.YES.getCode());
            messageSet.setFocusTip(YesNoStatus.YES.getCode());
            messageSet.setSysTip(YesNoStatus.YES.getCode());
            messageSet.setActTip(YesNoStatus.YES.getCode());
            messageSet.setGoodsTip(YesNoStatus.YES.getCode());
            messageSet.setMemberId(dbMember.getId());
            messageSetService.insert(messageSet);//保存push消息提示
        }

        MessageSetOutput output = MessageSetOutput.transform(messageSet);

        return output;

    }

    public boolean updateMessageSet(MessageSetOutput input, HttpServletRequest request) {
        CurrentUser currentUser = currentUserBizService.getCurrentUser(request);
        Member dbMember = memberService.get(currentUser.getId());
        //验证当前登录用户数据
        if (null == dbMember) {
            throw new BusinessException(PartyCode.CURRENT_USER_DATA_ERROR, "当前用户数据错误,请重新登录");
        }
        MessageSet messageSet = messageSetService.findByMemberId(dbMember.getId());

        if (null == messageSet) {
            messageSet = new MessageSet();
            messageSet.setLoveTip(YesNoStatus.YES.getCode());
            messageSet.setCommentTip(YesNoStatus.YES.getCode());
            messageSet.setFocusTip(YesNoStatus.YES.getCode());
            messageSet.setSysTip(YesNoStatus.YES.getCode());
            messageSet.setActTip(YesNoStatus.YES.getCode());
            messageSet.setGoodsTip(YesNoStatus.YES.getCode());
            messageSet.setMemberId(dbMember.getId());
            messageSetService.insert(messageSet);//保存push消息提示
        }

        //将输入的非空字段copy到MessageSet实体中
        BeanUtils.copyProperties(input, messageSet);
        return messageSetService.update(messageSet);
    }

    /**
     * 手机注册用户绑定第三方授权用户
     *
     * @param thirdPartyUserInput
     * @param request
     * @return
     */
    public MemberOutput bindThird(ThirdPartyUserInput thirdPartyUserInput,
                                  HttpServletRequest request) {
        CurrentUser currentUser = currentUserBizService.getCurrentUser(request);//根据token获取当前登录用户
        Member curMember = memberService.get(currentUser.getId());
        ThirdPartyUser tUser = thirdPartyUserService.getByOpenId(thirdPartyUserInput.getOpenId());
        if (null != tUser) {//授权用户存在
            thirdPartyUserService.delete(tUser.getId());
        }
        List<ThirdPartyUser> tpUsers = thirdPartyUserService.getTypeUser(thirdPartyUserInput.getType(), currentUser.getId());
        if (null == tpUsers || tpUsers.size() == 0) {
            ThirdPartyUser dbtUser = new ThirdPartyUser();
            dbtUser.setType(thirdPartyUserInput.getType());//第三方账号类型
            dbtUser.setMemberId(currentUser.getId());
            dbtUser.setThirdPartyId(thirdPartyUserInput.getOpenId());
            dbtUser.setType(thirdPartyUserInput.getType());
            dbtUser.setDelFlag(BaseModel.DEL_FLAG_NORMAL);
            dbtUser.setUnionId(thirdPartyUserInput.getUnionId());
            dbtUser.setAppId(wechatOpenMemberService.getSystem().getAuthorizerAppid());
            thirdPartyUserService.insert(dbtUser);//保存微信登陆openID
        }
        boolean bResult = false;
        if (Strings.isNullOrEmpty(curMember.getLogo()) && !Strings.isNullOrEmpty(thirdPartyUserInput.getLogo())) {
            curMember.setLogo(thirdPartyUserInput.getLogo());
            bResult = true;
        }
        //如果之前用户没有名字，则补充用户名字
        if (Strings.isNullOrEmpty(curMember.getRealname()) && !Strings.isNullOrEmpty(thirdPartyUserInput.getRealname())) {
            //过滤Emoji表情
            curMember.setRealname(PinyinUtil.filterEmoji(thirdPartyUserInput.getRealname(), ""));
            curMember.setPinyin(PinyinUtil.hanziToPinyin(curMember.getRealname(), ""));
            bResult = true;
        }
        //更新会员信息
        if (bResult) {
            memberService.update(curMember);
        }
        MemberOutput memberOutput = new MemberOutput();
        memberOutput = MemberOutput.transform(curMember);
        String token = this.getToken(curMember, currentUser.getOpenId());
        memberOutput.setToken(token);
        //设置第三方登录id列表
//        memberOutput.setThirdPartyUserList(this.getThirdPartyUser(currentUser.getId()));
        return memberOutput;
    }

    /**
     * 获取登陆用户详情
     *
     * @param currentUser 当前用户
     * @return 登陆用户详情
     */
    public MemberOutput getLoginMember(CurrentUser currentUser) {
        if (null != currentUser.getIsMemberGroup()) {
            if (YesNoStatus.YES.getCode().equals(currentUser.getIsMemberGroup())) {
                MemberGroup memberGroup = memberGroupService.get(currentUser.getId());
                return this.getLoginMember(memberGroup);
            } else if (YesNoStatus.NO.getCode().equals(currentUser.getIsMemberGroup())) {
                Member member = memberService.get(currentUser.getId());
                return this.getLoginMember(member);
            }
        }
        Member member = memberService.get(currentUser.getId());
        return this.getLoginMember(member);
    }

    /**
     * 更新用户头像
     *
     * @param member
     * @param logo
     */
    public void updateLogo(Member member, String logo) {
        String remoteUrl = "image.myqcloud.com";

        //旧的逻辑：
        //传入的头像不是万象优图的路径且backlogo为空或不是万象优图的路径
        //backlogo为空说明用户第一次登录，backlogo不是万象优图路径说明用户没有自己上传头像
        //if (StringUtils.isNotEmpty(logo) && logo.indexOf(remoteUrl) == -1 && (Strings.isNullOrEmpty(member.getBacklogo()) || member.getBacklogo().indexOf(remoteUrl) == -1))

        //新的逻辑：
        //传入的头像不是万象优图的路径 且 ( backlogo为空 或 原来的图片的宽度是150 )

        Map<String, Integer> imageWidthAndHeight = cosBizService.getImageWidthAndHeight(member.getLogo());
        Integer width = imageWidthAndHeight.get("width");

        logger.info("更新用户头像：原图", member.getLogo());
        logger.info("更新用户头像：当前图", logo);
        logger.info("更新用户头像：原图宽度：", width);
        if (StringUtils.isNotEmpty(logo) && logo.indexOf(remoteUrl) == -1 && (Strings.isNullOrEmpty(member.getBacklogo()) || (width > 131 && width < 151))) {
            //比对传入的logo和当前用户的backlogo
            if (!logo.equals(member.getBacklogo())) {
                String mLogo = member.getLogo();
                //更新logo和backlogo为微信头像
                member.setBacklogo(logo);
                member.setLogo(logo);
                memberService.update(member);
                //异步调用头像上传，回调更新logo为我们服务器的路径
                new Request(new RequestContent() {
                    @Override
                    void doSomeThing() {
                        try {
                            CompressInput compressInput = new CompressInput();
                            try {
                                int imageLength = cosBizService.getImageLength(logo);
                                if (imageLength > (1024 * 100)) {
                                    // 图片压缩参数
                                    compressInput.setMaxWidth(440);
                                    compressInput.setStrUrl(logo);
                                } else {
                                    compressInput = null;
                                }
                            } catch (Exception e) {
                                logger.error("获取图片大小异常", e);
                                // 图片压缩参数
                                compressInput.setMaxWidth(440);
                                compressInput.setStrUrl(logo);
                            }
                            logger.info("更新用户头像：图片压缩参数：", JSONObject.toJSONString(compressInput));
                            Map uploadRet = cosBizService.uploadImgRemote(logo, member.getId(), "", compressInput);
                            logger.info("更新用户头像： 上传结果：", JSONObject.toJSONString(uploadRet));
                            if (null != uploadRet) {
                                Map<String, Object> urlRet = cosBizService.handelImgUrl((Map) uploadRet.get("data"));
                                member.setLogo((String) urlRet.get("cdnUrl"));
                                memberService.update(member);
                                if(!mLogo.contains("1490783498894")){
                                    //删除更新前的用户头像
                                    if (!Strings.isNullOrEmpty(mLogo)) {
                                        cosBizService.delImgByCosPath(mLogo);
                                    }
                                }
                            }
                        } catch (Exception e) {
                            logger.error("更新用户头像异常", e);
                        }
                    }
                }).start();
            }
        }
    }

    /**
     * 获取省市区中文名 空格拼接
     *
     * @param provinceId 省份
     * @param cityId     城市
     * @param regionId   区域
     * @return
     */
    public String getShowAddress(String provinceId, String cityId, String regionId) {
        String showAddress = "";
        if (StringUtils.isNotEmpty(provinceId)) {
            Area area = areaService.get(provinceId);
            showAddress += area.getName() + " ";
        }
        if (StringUtils.isNotEmpty(cityId)) {
            Area area = areaService.get(cityId);
            showAddress += area.getName() + " ";
        }
        if (StringUtils.isNotEmpty(regionId)) {
            Area area = areaService.get(regionId);
            showAddress += area.getName();
        }
        return showAddress;
    }

    /**
     * 获取用户地址 先默认地址，默认地址没有则获取用户最新的地址
     *
     * @param memberId 用户id
     * @return
     * @throws Exception
     */
    public MemberAddressOutput getMemberAddress(String memberId) throws Exception {
        // 地址
        MemberAddress memberAddress = memberAddressService.getDefaultAddress(memberId);
        if (memberAddress == null) {
            memberAddress = memberAddressService.getBestNew(memberId);
        }
        if (memberAddress != null) {
            MemberAddressOutput addressOutput = MemberAddressOutput.transform(memberAddress);
            return addressOutput;
        } else {
            return null;
        }
    }

    /**
     * 用户设置信息
     *
     * @param memberId 用户id
     * @return
     */
    public MemberSetOutput getMemberSetInfo(String memberId) {
        MemberSet memberSet = this.getMemberSet(memberId);
        MemberSetOutput output = MemberSetOutput.transform(memberSet);
        return output;
    }

    /**
     * 设置jpush开关
     *
     * @param switchResult 选择结果
     * @param type         开关类型 1：活动 2：众筹报名 3：众筹成功 4：重要通知
     * @param memberId     用户id
     * @return
     */
    public MemberSetOutput updateMemberSetInfo(Integer switchResult, Integer type, String memberId) {
        MemberSet memberSet = this.getMemberSet(memberId);
        switch (type) {
            case 1:
                memberSet.setActivitySwitch(switchResult);
                break;
            case 2:
                memberSet.setCrowdfundApplySwitch(switchResult);
                break;
            case 3:
                memberSet.setCrowdfundSuccessSwitch(switchResult);
                break;
            case 4:
                memberSet.setImportantNotifySwitch(switchResult);
                break;
            default:
                break;
        }

        memberSetService.update(memberSet);

        return MemberSetOutput.transform(memberSet);
    }

    /**
     * 获取用户设置信息
     *
     * @param memberId 用户id
     * @return
     */
    public MemberSet getMemberSet(String memberId) {
        return memberSetService.initMemberSet(memberId);
    }

    /***
     * 获取当前月份的季度开始时间
     * @Date 17:33 2019/10/12
     * @param c
     * @return
     **/
    private static Date getCurrentQuarterStartTime(Calendar c) {
        SimpleDateFormat shortSdf = new SimpleDateFormat("yyyy-MM-dd");
        SimpleDateFormat longSdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");

        int currentMonth = c.get(Calendar.MONTH) + 1;

        Date now = null;
        try {
            if (currentMonth >= 1 && currentMonth <= 3) {
                c.set(Calendar.MONTH, 0);
            } else if (currentMonth >= 4 && currentMonth <= 6) {
                c.set(Calendar.MONTH, 3);
            } else if (currentMonth >= 7 && currentMonth <= 9) {
                c.set(Calendar.MONTH, 4);
            } else if (currentMonth >= 10 && currentMonth <= 12) {
                c.set(Calendar.MONTH, 9);
            }
            c.set(Calendar.DATE, 1);
            now = longSdf.parse(shortSdf.format(c.getTime()) + " 00:00:00");
        } catch (Exception e) {
            e.printStackTrace();
        }
        return now;

    }

    /***
     *  格式化参数，添加参数
     * @param mmp
     * @param timeType
     * @param integralTypeId
     * @return
     **/
    public void appendParams(Map<String, Object> mmp, Integer timeType, String integralTypeId) {

        /******** 时间块处理 ********/
        if (timeType != null && timeType != 0) {
            SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
            Calendar calendar = Calendar.getInstance();
            Date ed = calendar.getTime(); // 结束时间
            if (timeType == 1) { // 本月内
                calendar.set(Calendar.DAY_OF_MONTH, 1);
            } else if (timeType == 2) { // 本季度
                Date currentQuarterStartTime = getCurrentQuarterStartTime(calendar);
                calendar.setTime(currentQuarterStartTime);
            } else if (timeType == 3)  //本年
            {
                calendar.set(Calendar.DAY_OF_YEAR, 1);
            } else if (timeType == 4) { //本周
                int day_of_week = calendar.get(Calendar.DAY_OF_WEEK) - 1;
                if (day_of_week == 0) {
                    day_of_week = 7;
                }
                calendar.add(Calendar.DATE, -day_of_week + 1);
            }
            Date sd = calendar.getTime(); // 开始时间
            String std = sdf.format(sd) + " 00:00:00";
            mmp.put("startDate", std);
            String end = sdf.format(ed) + " 23:59:59";
            mmp.put("endDate", end);
        }
        /******** 时间块处理 ********/

        //处理积分类型
        if (StringUtils.isNotEmpty(integralTypeId)) {
            mmp.put("typeId", integralTypeId);
        }
    }


    /**
     * @Description: 获取行知公社主账号
     * @Param:
     * @return:MemberGroup
     * @Author: Hua Qunhao
     * @Date: 2019/11/12
     */
    public MemberGroup getXingZheGongSheMemberGroup() throws BusinessException {
        SysConfig xzgsConfig = sysConfigService.findByCode("XZGSID");
        if (xzgsConfig == null || StringUtils.isEmpty(xzgsConfig.getValue())) {
            throw new BusinessException("未设置行知公社主账号id");
        }
        MemberGroup memberGroup = memberGroupService.get(xzgsConfig.getValue());
        if (memberGroup == null) {
            throw new BusinessException("行知公社主账号id设置有误");
        }
        return memberGroup;
    }
}

class Request {
    private RequestContent rc;//请求主体

    public Request(RequestContent rc) {
        this.rc = rc;
    }

    protected void start() { //开始请求
        final Thread t = new Thread(() -> {
            try {
                rc.doSomeThing();//响应请求
            } catch (Exception e) {
                e.printStackTrace();
                rc.onFailure(); //如果执行失败
            }
            rc.onSuccess();//如果执行成功
        });
        t.start();
    }
}

abstract class RequestContent {
    void onSuccess() {  //执行成功的动作。用户可以覆盖此方法
        System.out.println("onSuccess");
    }

    void onFailure() { //执行失败的动作。用户可以覆盖此方法
        System.out.println("onFailure");
    }

    abstract void doSomeThing(); //用户必须实现这个抽象方法，告诉子线程要做什么
}

